package org.example;

import java.io.FileInputStream;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

public class NewIOClient {

    public static void main(String[] args) throws Exception {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress("localhost", 7001));
        String filename = "C:\\Users\\25459\\Desktop\\study\\my_netty\\src\\main\\resources\\test";
        //得到一个文件channel
        FileChannel fileChannel = new FileInputStream(filename).getChannel();

        long fileSize = fileChannel.size();
        long position = 0;
        long count;
        final long MAX_TRANSFER_SIZE = 8 * 1024 * 1024; // 8MB

        long startTime = System.currentTimeMillis();

        while (position < fileSize) {
            long remaining = fileSize - position;
            long transferSize = Math.min(remaining, MAX_TRANSFER_SIZE);
            count = fileChannel.transferTo(position, transferSize, socketChannel);
            if (count <= 0) break; // 传输失败或结束，防止死循环
            position += count;
        }

        long endTime = System.currentTimeMillis();
        System.out.println("发送的总字节数 = " + position + "，耗时 = " + (endTime - startTime) + " ms");

        //关闭
        fileChannel.close();
    }
}